package vn.edu.saigontech.ncms.service.impl;

import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;

import vn.edu.saigontech.ncms.model.info.ReceiptInfo;
import vn.edu.saigontech.ncms.service.ReceiptInfoService;
import vn.edu.saigontech.ncms.util.Checker;

public class ReceiptInfoServiceImpl extends HibernateGenericService<ReceiptInfo, Long> implements ReceiptInfoService {
	
	@Override
	public String generateReceiptInfoName(String name, String levelNotation, String discountNotation, int year) {
		StringBuilder buffer = new StringBuilder();
		ReceiptInfo receiptInfo = ReceiptInfoService.INSTANCE.find(name, year);
		if (Checker.isNull(receiptInfo)) {
			receiptInfo = ReceiptInfoService.INSTANCE.persist(new ReceiptInfo(
					name, year, 0));
		}
		buffer.append(name);
		if(levelNotation != null) {
			if(!levelNotation.isEmpty()) {
				buffer.append("-" + levelNotation);
			}
		}
		if(discountNotation != null) {
			if(!discountNotation.isEmpty()) {
				buffer.append(" " + discountNotation);
			}
		}
		buffer.append(" ");
		String sYear = String.valueOf(year);
		buffer.append(sYear.subSequence(2, sYear.length()));
		buffer.append(generateNextOrder(receiptInfo));
		return buffer.toString();
	}
	
	private String generateNextOrder(ReceiptInfo receiptInfo) {
		int nextOrder = Integer.valueOf(receiptInfo.getValue()) + 1;
		receiptInfo.setValue(nextOrder);
		ReceiptInfoService.INSTANCE.persist(receiptInfo);
		return formatOrder(nextOrder);
	}
	
	private String formatOrder(int order) {
		String sOrder = String.valueOf(order);
		int add = 4 - sOrder.length();
		for(int i = 0; i < add; i++) {		
			sOrder = "0" + sOrder;
		}
		return sOrder;
	}
	
	@Override
	public ReceiptInfo find(String name, int year) {
		Criteria criteria = this.createCriteria();
		criteria.add(Restrictions.eq("name", name));
		criteria.add(Restrictions.eq("year", year));
		return (ReceiptInfo) criteria.uniqueResult();
	}
}